import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  HttpStatus,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface ApiResponse<T = any> {
  code: number;
  success: boolean;
  message: string;
  data: {} & T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ApiResponse<T>> {
    // 类型守卫函数：检查数据是否为包含result属性的对象
    const isResultWrapper = (data: any): data is { result: T } => {
      return typeof data === 'object' && data !== null && 'result' in data;
    };

    return next.handle().pipe(
      map((data: T | { result: T } | undefined) => {
        // 使用类型守卫安全检查result属性并处理undefined情况
        const responseData = isResultWrapper(data)
          ? data.result
          : ((data ?? {}) as T);
        const { success, message, ...rest } = responseData as {
          success?: boolean;
          message?: string;
          [key: string]: any;
        };
        return {
          code: HttpStatus.OK,
          success: success ?? true,
          message: message || '请求成功',
          data: Array.isArray(responseData) ? responseData : { ...rest }
        } as ApiResponse<T>;
      }),
    );
  }
}
